using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ORS.OrderRobot.Domain;
using ORS.OrderRobot.EFCore.Repository;

namespace ORS.OrderRobot.EFCore;

public static class ServiceCollectionExtensions
{
    /// <summary>
    /// 仓储注册
    /// </summary>
    /// <param name="services"></param>
    /// <param name="configuration"></param>
    /// <returns></returns>
    public static IServiceCollection AddDataLayer(
        this IServiceCollection services,
        IConfiguration configuration)
    {
        // 注册数据库上下文
        services.AddDbContext<OrsDbContext>(options =>
        {
            var connectionString = configuration.GetConnectionString(Consts.ConnectName);
            if(connectionString == null)
            {
                throw new  Exception("连接配置为空");
            }
            options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
        });

        // 注册通用仓储
        services.AddScoped(typeof(IRepository<,>), typeof(EfCoreRepository<,>));
        services.AddScoped<IOrderRepository, OrderRepository>();
        services.AddScoped<IAccountBoardingRepository, AccountBoardingRepository>();
        return services;
    }
}
